<template>
  <div id="head">
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        :ellipsis="false"
        @select="handleSelect"
    >
      <el-menu-item index="0" style="margin-left: 6px">
        <img
            style="width: 40px"
            src="@/assets/医师汇.png"
            alt="Element logo"
        />
        <h2 style="color: var(--el-text-color-regular);margin-left: 5px">中药进销存ProMax</h2>
      </el-menu-item>
      <el-button type="success" style="margin-top: 15px;margin-right: 10px"  circle @click="toAi" > Ai</el-button>
      <el-menu-item index="1">{{ route.meta.name}}</el-menu-item>
      <el-row class="demo-avatar demo-basic" @click="showUploadDialog">
        <el-col :span="12">
          <div class="demo-basic--circle">
              <el-avatar :size="35" :src="circleUrl" />
              <div class="sub-title">{{ data.user.username}}</div>
          </div>
        </el-col>
      </el-row>
      <!-- 上传对话框 -->
      <el-dialog v-model="isUploadDialogVisible" title="更换头像">
        <el-upload
            action="http://localhost:8080/files/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :auto-upload="true"
            multiple="false"
        >
          <el-button type="primary">选择头像文件</el-button>
        </el-upload>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="isUploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="isUploadDialogVisible = false">确定</el-button>
        </span>
        </template>
      </el-dialog>
      <el-sub-menu index="2">
        <template #title>设置</template>
        <el-menu-item index="2-1" @click="toPassword">
          <el-icon><WarningFilled /></el-icon>
          修改密码
        </el-menu-item>
        <el-menu-item index="2-2" @click="toPerson">
          <el-icon><WarningFilled /></el-icon>
          修改个人信息
        </el-menu-item>
        <el-menu-item index="2-3" @click="logout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
  <div style="display: flex">
    <!--  左侧菜单栏-->
    <div style="width: 180px;height: calc(100vh - 60px);border-right:1px solid var(--el-menu-border-color)">
      <el-row class="tac">
        <el-col :span="12">
          <el-menu
              :default-active="router.currentRoute.value.path"
              class="el-menu-vertical-demo"
              @open="handleOpen"
              @close="handleClose"
              router
          >
            <el-menu-item index="/manager/home">
              <el-icon><icon-menu /></el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-sub-menu index="1" v-if=" data.user.role=='admin' ">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>管理中心</span>
              </template>
              <el-menu-item index="/manager/user" >用户管理</el-menu-item>
              <el-menu-item index="/manager/operation">操作日志</el-menu-item>
              <el-menu-item index="/manager/apply">申请处理</el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <el-icon><location /></el-icon>
                <span>库存中心</span>
              </template>
              <el-menu-item index="/manager/category" v-if=" data.user.role =='merchant' || data.user.role =='admin' " >品类管理</el-menu-item>
              <el-menu-item index="/manager/data" v-if=" data.user.role=='merchant' || data.user.role=='admin'" >药材管理</el-menu-item>
              <el-menu-item index="/manager/income" v-if="  data.user.role=='admin'" >入库管理</el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="3" v-if="data.user.role =='admin' ">
              <template #title>
                <el-icon><document /></el-icon>
                <span>销售中心</span>
              </template>
<!--              <el-menu-item index="/manager/addShop">药材中心</el-menu-item>-->
              <el-menu-item index="/manager/shopCar">购物车</el-menu-item>
              <el-menu-item index="/manager/orderManage">订单管理</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-col>
      </el-row>
    </div>
    <!--  右侧内容-->
    <div style="flex: 1;width: 0;padding: 10px;">
            <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import router from '../router/index.js'
import { reactive, toRefs } from 'vue'
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/utils/request.js';
const route = useRoute();
const toAi =()=>{
  router.push('/manager/chat')
}
const toPerson= () =>{
  router.push('/manager/person');
}
const toPassword=() =>{
  router.push('/manager/password');
}

const logout = () => {
  // 使用 post 方法发送请求
  request.post('/user/logout').then(res => {
    console.log(res);
    // 假设后端返回的是 JSON 格式数据，并且有一个 code 字段表示状态码
    if (res.code === 200) {
      sessionStorage.removeItem("user-name");
      localStorage.removeItem("root_token");
      ElMessage.success("退出成功！");
      router.push('/');
    } else {
      ElMessage.error("退出失败");
    }
  }).catch(error => {
    console.error('请求出错:', error);
    ElMessage.error("请求出错，请稍后重试");
  });
};
const activeIndex = ref('1')
const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const data = reactive({
  user:JSON.parse(sessionStorage.getItem('user-Info'))
})
import {
  Document,
  Menu as IconMenu,
  Location,
  SwitchButton,
  WarningFilled, Setting
} from '@element-plus/icons-vue'
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

// 定义响应式状态
const state = reactive({
  // 从 localStorage 中获取头像 URL，如果没有则使用默认值
  circleUrl: JSON.parse(localStorage.getItem('head-url')) || 'your-default-avatar-url',
  sizeList: ['small'] as const,
});

const { circleUrl} = toRefs(state)

//上传头像
// 上传对话框是否可见
const isUploadDialogVisible = ref(false);

// 点击头像时显示上传对话框
const showUploadDialog = () => {
  isUploadDialogVisible.value = true;
};
// 上传成功回调
const handleUploadSuccess = (response) => {
  // 更新 localStorage 中的头像 URL
  localStorage.setItem('head-url', JSON.stringify(response.data));
  // 更新 circleUrl 的值，使页面上的头像立即更新
  circleUrl.value = response.data;
  ElMessage.success('头像更换成功');
  // 关闭上传对话框
  isUploadDialogVisible.value = false;
};
// 上传失败回调
const handleUploadError = () => {
  ElMessage.error('头像更换失败，请重试');
};
// 上传前的处理，例如限制文件类型和大小
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('只能上传 JPG 或 PNG 格式的图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }
  return true;
};
</script>

<style scoped>
#head{
  height: 60px;
}
.el-menu--horizontal > .el-menu-item:nth-child(1) {
  margin-right: auto;
}
.el-col-12 {
  max-width: 100%;
  min-height: calc(100vh - 60px);
  border-right: #666666 !important;
}
.el-menu{
  border-right: none;
}
.demo-basic {
  text-align: center;
}
.demo-basic .sub-title {
  width: fit-content;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.demo-basic .demo-basic--circle,
.demo-basic{
  height: 60px;
  margin-left: 5px;
  display: flex;
  flex-direction: column;
  margin-top: 4px;
  margin-left: 10px;
  align-items: center;
}
.demo-basic .el-col:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
</style>
